package com.by.zhdoctor.web.rest;

import com.by.zhdoctor.domain.Topic;
import com.by.zhdoctor.repository.CommentRepository;
import com.by.zhdoctor.repository.TopicRepository;
import com.by.zhdoctor.service.dto.FileUploadDTO;
import com.by.zhdoctor.service.dto.TopicDTO;
import com.by.zhdoctor.service.dto.UploadResoultDTO;
import com.by.zhdoctor.service.util.ImageBase64Utils;
import com.by.zhdoctor.web.rest.util.HeaderUtil;
import com.by.zhdoctor.web.rest.util.PaginationUtil;
import com.codahale.metrics.annotation.Timed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Topic.
 */
@RestController
@RequestMapping("/api")
public class TopicResource {

    private final Logger log = LoggerFactory.getLogger(TopicResource.class);

    @Inject
    private TopicRepository topicRepository;
    @Inject
    private CommentRepository commentRepository;

    /**
     * POST  /topics : Create a new topic.
     *
     * @param topic the topic to create
     * @return the ResponseEntity with status 201 (Created) and with body the new topic, or with status 400 (Bad Request) if the topic has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/topics")
    @Timed
    public ResponseEntity<Topic> createTopic(@RequestBody Topic topic) throws URISyntaxException {
        log.debug("REST request to save Topic : {}", topic);
        if (topic.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("topic", "idexists", "A new topic cannot already have an ID")).body(null);
        }
        Topic result = topicRepository.save(topic);
        return ResponseEntity.created(new URI("/api/topics/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("topic", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /topics : Updates an existing topic.
     *
     * @param topic the topic to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated topic,
     * or with status 400 (Bad Request) if the topic is not valid,
     * or with status 500 (Internal Server Error) if the topic couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/topics")
    @Timed
    public ResponseEntity<Topic> updateTopic(@RequestBody Topic topic) throws URISyntaxException {
        log.debug("REST request to update Topic : {}", topic);
        if (topic.getId() == null) {
            return createTopic(topic);
        }
        Topic result = topicRepository.save(topic);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("topic", topic.getId().toString()))
            .body(result);
    }

    /**
     * GET  /topics : get all the topics.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of topics in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/topics")
    @Timed
    public ResponseEntity<List<Topic>> getAllTopics(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Topics");
        Page<Topic> page = topicRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/topics");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /topics/:id : get the "id" topic.
     *
     * @param id the id of the topic to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the topic, or with status 404 (Not Found)
     */
    @GetMapping("/topics/{id}")
    @Timed
    public ResponseEntity<Topic> getTopic(@PathVariable Long id) {
        log.debug("REST request to get Topic : {}", id);
        Topic topic = topicRepository.findOne(id);
        return Optional.ofNullable(topic)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /topics/:id : delete the "id" topic.
     *
     * @param id the id of the topic to delete
     * @return the ResponseEntity with status 200(OK)
     */
    @DeleteMapping("/topics/{id}")
    @Timed
    @Transactional
    public ResponseEntity<Void> deleteTopic(@PathVariable Long id) {
        log.debug("REST request to delete Topic : {}", id);
//        Topic topic=neTw Topic();
//        topic.setId(id);
//        List<Comment> commentList=commentRepository.findByTopic(topic);
//        commentRepository.delete(commentList);
//        log.debug("commentList:{}",commentList.size());
        commentRepository.deleteByTopicId(id);
        log.debug(" 删除评论成功");
        topicRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("topic", id.toString())).build();
    }


    /**
     * GET  /topics-community/:comunity : get the "id" topic.
     *
     * @param comunity the id of the topic to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the topic, or with status 404 (Not Found)
     */
    @GetMapping("/topics-community/{comunity}")
    @Timed
    public ResponseEntity<List<Topic>> getTopicfromcommunity(@PathVariable String comunity,Pageable pageable) throws URISyntaxException {
        log.debug("REST request to get Topic : {}", comunity);
        Page<Topic> page = topicRepository.findBycomunity(comunity,pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/topics-community");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }



    /**
     * POST  /uploadImgBase : Upload Image by Base64.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of userquestions in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @RequestMapping(value="/uploadImgBase", method= RequestMethod.POST)
    public ResponseEntity<UploadResoultDTO> handleImageUpload(@Valid @RequestBody FileUploadDTO fileUploadDTO){
        final Logger log = LoggerFactory.getLogger(TopicResource.class);
        log.info(fileUploadDTO.getFile());
        String file=fileUploadDTO.getFile();
        String filename=fileUploadDTO.getFilename();
        String truePath="C:\\Program Files\\Apache Software Foundation\\Tomcat 9.0\\webapps\\zhserver\\content\\uploadImages\\"+filename;
        Boolean isSave= ImageBase64Utils.base64ToImageFile(file,truePath);
        if (isSave){
//            Map<String, String> map = new HashMap<>();
//            map.put("link","http://218.65.178.146:8070/yz_server/content/uploadImages/"+filename);
            String link="http:]]218.65.178.146:9090]zhserver]content]uploadImages]"+filename;
            UploadResoultDTO uploadResoultDTO=new UploadResoultDTO();
            uploadResoultDTO.setLink(link);
            return ResponseEntity.ok()
                .body(uploadResoultDTO);
        }else {
            return new ResponseEntity<UploadResoultDTO>(HttpStatus.BAD_REQUEST);
        }

    }

    /**
     * GET  /topics-community-withAvatar/:comunity : get the "id" topic.
     *
     * @param comunity the id of the topic to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the topic, or with status 404 (Not Found)
     */
    @GetMapping("/topics-community-withAvatar/{comunity}")
    @Timed
    public ResponseEntity<List<TopicDTO>> getTopicwithAvatarbycommunity(@PathVariable String comunity,Pageable pageable) throws URISyntaxException {
        log.debug("REST request to get Topic : {}", comunity);
        Page<TopicDTO> page = topicRepository.getTopicwithAvatarbycommunity(comunity,pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/topics-community-withAvatar");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }
    /**
     * GET  /topics-community/topics-count/:community : get the "community" topic count.
     *
     * @param community the id of the topic to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the topic, or with status 404 (Not Found)
     */
    @GetMapping("/topics-community/topics-count/{community}")
    @Timed
    public ResponseEntity<Integer> getTopicsCountforCommunity(@PathVariable String community) throws URISyntaxException {
        log.debug("REST request to get Topic : {}", community);
        int count = topicRepository.findBycomunity(community).size();
        return Optional.ofNullable(count)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * GET  /topics : get all the hot topics.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of topics in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @GetMapping("/topic")
    @Timed
    public ResponseEntity<List<TopicDTO>> getAllTopic(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of Topics");
        Page<TopicDTO> page = topicRepository.findAllTopic(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/topic");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }
}
